package com.shaozi.nc.quartz.manage;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.log4j.Logger;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.shaozi.common.schedule.DyncQuartzManage;
import com.shaozi.nc.core.Consts;
import com.shaozi.nc.data.hibVO.AttendanceLevelVO;
import com.shaozi.nc.quartz.attendance.AttendanceSignJob;
import com.shaozi.utils.date.DateHelper;

@Service
public class AttendanceSignRuleManage {

	@Value("${attendance.alarm.start.diff.min:10}")
	private int startDiffMin;

	private Logger logger = Logger.getLogger(AttendanceSignRuleManage.class);

	@Autowired
	private DyncQuartzManage dyncQuartzMgr;

	public void scheduleByAttendanceLevel(List<AttendanceLevelVO> levelVOs, String companyId)
			throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, SchedulerException {
		this.commonScheduleByAttendanceLevel(levelVOs, companyId, false);
	}

	/**
	 * 观察者 入口
	 */
	public void scheduleByAttendanceLevelAndObserver(List<AttendanceLevelVO> levelVOs, String companyId)
			throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, SchedulerException {
		this.commonScheduleByAttendanceLevel(levelVOs, companyId, true);
	}

	public void commonScheduleByAttendanceLevel(List<AttendanceLevelVO> levelVOs, String companyId, boolean isObserver)
			throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, SchedulerException {
		if (levelVOs.isEmpty()) {
			logger.info("load attendance level empty: " + companyId);
			return;
		}
		String[] inout = { "in", "out" };
		for (AttendanceLevelVO vo : levelVOs) {
			int type = Consts.Attendance.Type_In;
			for (String io : inout) {
				try {
					String punchTime = (String) PropertyUtils.getSimpleProperty(vo, "punsh_" + io + "_time");
					if (StringUtils.isEmpty(punchTime))
						continue;
					long startAt = DateHelper.withStartAt(punchTime, Consts.Attendance.Type_Out, type, startDiffMin);
					// if (startAt < System.currentTimeMillis()) {
					// continue;
					// }
					if (startAt < System.currentTimeMillis()) {
						// 延迟一分钟调度任务执行 依据当前系统时间 延迟一分钟执行
						startAt = System.currentTimeMillis() + (1000L * 60);
					}
					logger.info("scheduleByAttendanceLevel to addAttendanceSignJob companyId:" + companyId + ",io:" + io
							+ ",vo:" + vo.toString() + ",punchTime:" + punchTime + ",type:" + type + ",startAt:"
							+ startAt);
					addAttendanceSignJob(companyId, io, vo, punchTime, type, startAt, isObserver);
				} finally {
					type++;
				}
			}
		}
		logger.info("companyId=" + companyId + ";level size=" + levelVOs.size());
	}

	private void addAttendanceSignJob(String companyId, String io, AttendanceLevelVO vo, String punchTime, int type,
			long startAt, boolean isObserver) throws SchedulerException {

		String jobName = String.format("%s.%s.%s.%d", companyId, "data.init", io, vo.getId());
		String triggerName = String.format("trigger.%s", jobName);
		String groupKey = "attendance";
		Map<String, String> dataMap = new HashMap<>();
		dataMap.put("companyId", companyId);
		dataMap.put("levelId", String.valueOf(vo.getId()));
		dataMap.put("punchTime", punchTime);
		dataMap.put("type", String.valueOf(type));
		dataMap.put("isObserver", String.valueOf(isObserver));
		dataMap.put(com.shaozi.nc.quartz.base.Consts.DataKey_StartAt, String.valueOf(startAt));
		if (dyncQuartzMgr.existTrigger(groupKey, triggerName)) {
			dyncQuartzMgr.removeJob(groupKey, jobName, groupKey, triggerName);
		}
		dyncQuartzMgr.addJobWithOnce(groupKey, jobName, AttendanceSignJob.class, groupKey, triggerName, startAt,
				dataMap);
	}

	public int getStartDiffMin() {
		return startDiffMin;
	}

	public void setStartDiffMin(int startDiffMin) {
		this.startDiffMin = startDiffMin;
	}

}
